﻿using Logistics.Commn.RabbitMQ;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace Logistics.Commn
{
    /// <summary>
    /// 交换机类型为Routing Key。在发布/订阅模式的基础上，有选择的接收消息，也就是通过 routing 路由进行匹配条件是否满足接收消息
    /// </summary>
    public class SendRouting
    {
        /// <summary>
        /// 路由模式，点到点直连队列
        /// </summary>
        public static void SendMessageDirect(string accountNumber,string mailbox, string randomNumber) 
        {
            //创建连接
            using (var connection = RabbitMQHelper.GetConnection())
            {
                //创建信道
                using (var channel = connection.CreateModel())
                {
                    //声明交换机对象,fanout类型
                    string exchangeName = "direct_exchange";
                    channel.ExchangeDeclare(exchangeName, ExchangeType.Direct);

                    //创建队列
                    string queueName = "direct_errorlog";
                    //删除队列
                    channel.QueueDelete(queueName);

                    channel.QueueDeclare(queueName, true, false, false);
                   
                    //把创建的队列绑定交换机,direct_errorlog队列只绑定routingKey:error
                    channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: "info");

                    var properties = channel.CreateBasicProperties();
                    properties.Persistent = true; //消息持久化
                    var message = new Mail()
                    {
                        AccountNumber = accountNumber,
                        Mailbox = mailbox,
                        RandomNumber = randomNumber
                    };
                    var body = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(message));
                    channel.BasicPublish(exchangeName, routingKey: "info", properties, body);
                }
            }
        }
    }
}